let MongoDBUtil = require('./../../../util/MongoDBUtil');
let Contants = require('./../data/Contants');
let RoomIdGenerator = require('./../../../util/RoomIdGenerator');
const MAP_ID = require('./../../../define/MAP_ID');
const MapID2ServerID = require('./../../../define/MapID2ServerID');

module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
};

/**
 * 创建一个新用户
 * @param {Object} data
 * @return {Object}
 * */
let createUser = function (data) {
    let o = {};
    o._id = data['uid'];
    o.login_type = 1;
    o.uid = 123456789;
    o.nickname = '游客' + o.uid;
    o.sex = 1;
    o.headimgurl = '';
    o.create_time = Date.now();
    o.last_login_time = Date.now();
    o.is_new = true;
    o.card_num = 5;
    o.gold_num = 10000;
    o.level = 0;
    o.is_native = 0;
    o.os = 'unkown';
    o.version = '0.0.0';
    o.native_version = '0.0.0';
    o.is_reconnect = false;

    // 赋值
    for (let key in data) {
        if (o.hasOwnProperty(key)) {
            o[key] = data[key];
        }
    }
    return o;
};

/**
 * New client entry chat server. 新客户端进入
 *
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {void}
 */
Handler.prototype.login = function (msg, session, next) {
    let self = this;
    let code = msg['code'];
    let data = msg['data'];
    let uid = data['uid'];

    if (!self.app.mongo) {
        next(null, {
            code: Contants.Code.Login,
            errorCode: Contants.ErrorCode.Login_DB_Error,
            data: {
                msg: Contants.CodeString[Contants.ErrorCode.Login_DB_Error]
            }
        });
        return;
    }

    let sessionService = self.app.get('sessionService');
    if (!!sessionService.getByUid(uid)) {
        next(null, {
            code: Contants.Code.Login,
            errorCode: Contants.ErrorCode.Other_Logined,
            data: {
                msg: Contants.CodeString[Contants.ErrorCode.Other_Logined]
            }
        });
        return;
    }

    // 查询数据库/更新数据库
    let update_data = {last_login_time: Date.now(), is_new: false};
    let allow_update_field = ['last_login_time', 'is_new', 'os', 'options', 'version', 'native_version', 'headimgurl', 'is_native'];
    for (let k in data) {
        if (data.hasOwnProperty(k)) {
            if (allow_update_field.indexOf(k)) {
                update_data[k] = data[k];
            }
        }
    }
    let info = createUser(data);
    let bindfunc = function () {
        session.bind(uid);
        // session.on('closed', onUserLeave.bind(null, self.app));
        session.on('closed', self.logout.bind(self, self.app));
        session.set('info', info);
        session.push('info', function (error) {
            if (error) {
                console.error('set rid for session service failed! error is : %j', error.stack);
            }
        });

        let is_reconnect = self.app.uid2roomid.hasOwnProperty(uid);
        let msgObj = {};
        msgObj.code = Contants.Code.Login;
        msgObj.data = data;
        msgObj.data.is_reconnect = is_reconnect;
        msgObj.data.room_id = self.app.uid2roomid[uid];
        next(null, msgObj);

        // 查询是否在房间中
        if (is_reconnect) {
            console.info('玩家【' + uid + '】在房间【' + self.app.uid2roomid[uid] + '】中，将要进行断线续玩');
            if (self.app.hasOwnProperty('roomHandler')) {
                let msg = {};
                msg.data = {
                    room_id: self.app.uid2roomid[uid],
                    uid: uid
                };
                self.app.roomHandler.joinRoom(msg, session);
            }
        }
        console.info('login', self.app.uid2roomid);
    };
    // let filter = {_id: uid};
    // let update = {$set: update_data};
    MongoDBUtil.findOneAndUpdate('users', {_id: uid}, {$set: update_data}, function (result, value) {
        if (!result) {
            MongoDBUtil.insertOne('users', info, function (err, value) {
                if (!err) {
                    bindfunc();
                }
            });
        } else {
            bindfunc();
        }
    });
};

/**
 * User log out handler. 用户注销处理
 * @param {Object} app current application
 * @param {Object} session current session object
 */
Handler.prototype.logout = function (app, session) {
    if (!app || !session) {
        return false;
    }

    let room_id = this.queryRoomByUid(session.uid);
    if (room_id !== '') {
        if (this.app.roomid2mapid.hasOwnProperty(room_id)) {
            let map_id = this.app.roomid2mapid[room_id];
            if (MapID2ServerID.hasOwnProperty(map_id)) {
                let targetServer = MapID2ServerID[map_id];
                app.rpc[targetServer].Remote.logout(session, session.uid, app.get('serverId'), room_id, null);
            }
        }
    }
    console.info('entryHandler用户【' + session.uid + '】注销了', room_id);
    // console.info('用户注销处理session', session);
    // console.info('用户注销处理sessionService', sessionService);
    return true;
};

/**
 * 查询该uid是否在房间中，在则返回房间号，否则返回""
 * @param {String} uid
 * @return {String | Number}
 * */
Handler.prototype.queryRoomByUid = function (uid) {
    if (this.app.uid2roomid.hasOwnProperty(uid)) {
        // console.info('玩家【' + uid + '】在房间【' + this.app.uid2roomid[uid] + '】中，将要进行断线续玩');
        return this.app.uid2roomid[uid];
    }
    return '';
};

var onUserLeave = function (app, session) {
    if (!session || !session.uid) {
        return;
    }
    console.log('玩家【' + session.uid + '】离线了！');

    // console.log(session.get("info"));
    let room_id = session.get('room_id');
    session.unbind(session.uid);
    console.log('onUserLeave room_id: ', room_id);
    if (room_id) {
        app.rpc.psz.pszRemote.kick(session, session.uid, app.get('serverId'), room_id, null);
    }

    let uid = session.uid;
    let sessionService = app.get('sessionService');
    if (sessionService) {
        sessionService.remove(session.sid);
    }
};